package com.smile.db.operation;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.smile.db.DBHelper;
import com.smile.model.RegisterBean;

public class RegisterOperation {

	private static final RegisterOperation RO = new RegisterOperation();

	private RegisterOperation() {
	}

	public static RegisterOperation getRO() {
		return RO;
	}

	public String insert(RegisterBean registerBean) {

		/**
		 * 插入语句
		 */
		String sqlInsert = "INSERT INTO `user` (`u_id`, `u_name`, `u_nickname`, `u_password`) VALUES (NULL,'"
				+ 0
				+ "','"
				+ registerBean.getName()
				+ "', '"
				+ registerBean.getPassword() + "')";

		/**
		 * 查询id语句
		 */
		String sqlSearch = "select u_id from user where u_nickname='"
				+ registerBean.getName() + "'";

		int result = -1;
		try {
			result = DBHelper.update(sqlInsert);

			if (result == 1) {
				ResultSet resultset = DBHelper.query(sqlSearch);
				if (resultset.next()) {
					int id = resultset.getInt("u_id");
					Date date = new Date();
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					String time = format.format(date).replaceAll("-", "") + id;
					// System.out.println(time);

					/**
					 * 更新帐号语句
					 */
					String sqlUpdate = "UPDATE `user` SET `u_name` = '" + time
							+ "' WHERE `user`.`u_id` = " + id;
					// System.out.println(sqlUpdate);

					result = DBHelper.update(sqlUpdate);
					if (result == 1) {
						return "1@" + time;
					} else {
						return "-1@" + result;
					}

				} else {
					return "-1@null";
				}
			} else {
				return "-1@" + result;
			}

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			return "-1@" + e.getErrorCode();
			// System.out.println(e.getErrorCode());
		}
	}
}
